'''
Created on Jul 07, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils.sent_logger import sent_logger
from StringIO import StringIO
from sent.opinion import process_nested_set_pending_operations
from sent.utils.result_printer import getPrinter
from sent.utils import CommonResult, ErrorIds
from sententialyzer.settings import DEBUG
import json

logger = sent_logger( __name__ )

class ProcessNestedSet(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        
        commit_delay=0
        if DEBUG:
            commit_delay = float(self.request.POST.get('commit_delay', 0))
            
        out_msg = StringIO()
        
        cmn_result = CommonResult()
        total_result = CommonResult()
        total_result.result = {}
        while cmn_result.errorId == ErrorIds.SUCCESS:
            cmn_result = process_nested_set_pending_operations(out_msg, commit_delay)
            
            if cmn_result.errorId == ErrorIds.SUCCESS and cmn_result.result:
                if total_result.result.has_key(cmn_result.result['base_id']):
                    prev_res = total_result.result[cmn_result.result['base_id']]
                    prev_res['deleted'] += cmn_result.result['deleted']
                    prev_res['created'] += cmn_result.result['created']
                    prev_res['updated'] += cmn_result.result['updated']
                else:
                    total_result.result[cmn_result.result['base_id']] = cmn_result.result.copy()
            
            if not cmn_result.result:
                cmn_result.result = {}
                
            logger.log(sent_logger.INFO, "Nested set processing completed. " 
                       + json.dumps(cmn_result.result) 
                       + " status: " + str(cmn_result.errorId)
                       + " output: " + out_msg.getvalue())
        
        total_result.errorId = ErrorIds.SUCCESS
        
        return getPrinter().printResult(total_result)
        
    